package com.ruoyi.web.controller.pdd;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsSaleStatusSetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsSaleStatusSetResponse;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.framework.config.webSocket.WebSocketServer;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.utils.PageUtils.startPage;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 拼多多商品Controller
 *
 * @author ruoyi
 * @date 2023-11-12
 */
@RestController
@RequestMapping("/system/pddGoods")
public class TlPddGoodsController extends BaseController
{
    @Autowired
    private ITlPddGoodsService tlPddGoodsService;
    @Autowired
    private ITlPddGoodsSkuService tlPddGoodsSkuService;
    @Autowired
    private ITlPddGoodsSpecService tlPddGoodsSpecService;
    @Autowired
    private ITlPddTokenService iTlPddTokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ITlPddMallService tlPddMallService;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${ruoyi.clientId}")
    private String clientId;
    @Value("${ruoyi.clientSecret}")
    private String clientSecret;



    @GetMapping("/list")
    public TableDataInfo list(TlPddGoods tlPddGoods) {
        startPage();
        List<TlPddGoodsVo> list = tlPddGoodsService.selectTlPddGoodsList(tlPddGoods);
        return getDataTable(list);
    }

    @GetMapping("/skuList")
    public TableDataInfo skuList(TlPddGoodsSku tlPddGoodsSku) {
        startPage();
        List<TlPddGoodsSkuVo> list = tlPddGoodsSkuService.selectTlPddGoodsSkuList(tlPddGoodsSku);
        return getDataTable(list);
    }

    @PostMapping("/jiankongPddData")
    public AjaxResult jiankongPddData(TlPddGoods tlPddGoods) throws Exception{

        //查询拼多多token
        Long userId = getLoginUser().getUserId();
        TlPddToken tlPddToken = iTlPddTokenService.selectTlPddTokenByUserIdAndoWnerId(tlPddGoods.getOwnerId().toString());

        //查询店铺信息
        TlPddMall tlPddMall = tlPddMallService.selectTlPddMallByMallId(tlPddGoods.getOwnerId());

        tlPddGoods.setUserId(userId);
        tlPddGoods.setOwnerId(tlPddMall.getMallId());
        List<TlPddGoodsVo> list = tlPddGoodsService.selectTlPddGoodsList(tlPddGoods);
        //使用webSocket把总数发送到前台
        JSONObject res = new JSONObject();
        res.put("action","total");
        res.put("total",list.size());
        webSocketServer.sendInfo(res.toJSONString(),userId.toString());

        //记录监控数量
        Integer count = 0;
        //记录需要下架的商品id。执行结束后统一删除
        ArrayList<Long> goodsIds = new ArrayList<>();

        for (TlPddGoodsVo vo : list)
        {
            //存下SKU
            TlPddGoodsSku tlPddGoodsSku = new TlPddGoodsSku();
            tlPddGoodsSku.setGoodId(vo.getGoodsId());
            List<TlPddGoodsSkuVo> skuList = tlPddGoodsSkuService.selectTlPddGoodsSkuList(tlPddGoodsSku);
            TlPddGoodsSkuVo skuVo = skuList.get(0);

            //先查询redis判断是否存在缓存
            TlDyDoodsDetail tlDyDoodsDetail = redisCache.getCacheObject(skuVo.getOuterGoodsId());
            if(tlDyDoodsDetail == null) {
                //获取详情数据
                String detail = HttpUtils.sendPost("https://www.zcxq.com/v1/leya/share/goods/detail/", "product_id=" + skuVo.getOuterGoodsId().split("-")[1]);
                JSONObject detailjsonObject =  JSONObject.parseObject(detail);
                String detailcode = detailjsonObject.getString("code");
                if(!detailcode.equals("200")){
                    //查不到商品，执行下架操作
                    if(tlPddMall.getXiajia().equals("1")) {
                        //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                        goodsIds.add(vo.getGoodsId());

                        //向前端发送下架信息
                        vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                        vo.setReason("联盟已下架");
                        count++;
                        res = new JSONObject();
                        res.put("action","list");
                        res.put("data",vo);
                        res.put("count",count);
                        webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                    } else {
                        count++;
                        res = new JSONObject();
                        res.put("action","tongbu");
                        res.put("count",count);
                        webSocketServer.sendInfo(res.toJSONString(),userId.toString());
                    }
                    continue;
                }
                //解析详情
                String detailData = detailjsonObject.getString("data");
                tlDyDoodsDetail = JSONObject.parseObject(detailData, TlDyDoodsDetail.class);

                redisCache.setCacheObject(skuVo.getOuterGoodsId(), tlDyDoodsDetail, 2, TimeUnit.MINUTES);
            }

            if(tlPddMall.getKucun().equals("1")) {
                if(tlDyDoodsDetail.getInStock() == 0) {
                    //如果没有库存，执行下架操作
                    //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                    //记录需要下架的商品id。执行结束后统一删除
                    goodsIds.add(vo.getGoodsId());

                    //向前端发送下架信息
                    vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                    vo.setReason("无库存");
                    count++;
                    res = new JSONObject();
                    res.put("action","list");
                    res.put("data",vo);
                    res.put("count",count);
                    webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                    continue;
                }
            }

            if(tlPddMall.getZhuanxiang().equals("1")) {
                if(tlDyDoodsDetail.getIsAssured() == 1) {
                    //如果是专向链接执行下架操作
                    //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                    //记录需要下架的商品id。执行结束后统一删除
                    goodsIds.add(vo.getGoodsId());

                    //向前端发送下架信息
                    vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                    vo.setReason("专向链接");
                    count++;
                    res = new JSONObject();
                    res.put("action","list");
                    res.put("data",vo);
                    res.put("count",count);
                    webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                    continue;
                }
            }

            if(tlPddMall.getYingli().equals("1")) {
                //计算金额
                BigDecimal yingli = tlDyDoodsDetail.getPrice().subtract(tlDyDoodsDetail.getOriginCosFee()).subtract(tlPddMall.getYingliyujing()).subtract(tlPddMall.getYouhuiquan());
                if(yingli.compareTo(BigDecimal.ZERO) < 0) {
                    //如果金额不符合标准执行下架操作
                    //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                    goodsIds.add(vo.getGoodsId());

                    //向前端发送下架信息
                    vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                    vo.setReason("盈利预警");
                    count++;
                    res = new JSONObject();
                    res.put("action","list");
                    res.put("data",vo);
                    res.put("count",count);
                    webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                    continue;
                }
            }

            //解析发货时间
            String[] arr = tlDyDoodsDetail.getLogisticsInfo().split("，");
            if(tlPddMall.getFahuo().equals("1")) {
                //判断是按天数，还是按小时
                if(tlDyDoodsDetail.getLogisticsInfo().contains("小时")) {
                    Integer time = arr.length == 2 ? Integer.valueOf(arr[0].replaceAll("[^0-9]", "")) : Integer.valueOf(arr[1].replaceAll("[^0-9]", ""));
                    if(time > 48) {
                        //如果发货时间大于48小时，执行下架操作
                        //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                        goodsIds.add(vo.getGoodsId());

                        //向前端发送下架信息
                        vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                        vo.setReason("发货时间超过48小时");
                        count++;
                        res = new JSONObject();
                        res.put("action","list");
                        res.put("data",vo);
                        res.put("count",count);
                        webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                        continue;
                    }
                } else {
                    //包含天数,判断是否是明天字样
                    if(!tlDyDoodsDetail.getLogisticsInfo().contains("明天")) {
                        Integer time =  arr.length == 2 ? Integer.valueOf(arr[0].replaceAll("[^0-9]", "")) : Integer.valueOf(arr[1].replaceAll("[^0-9]", ""));
                        if(time > 2) {
                            //如果发货时间大于2天，执行下架操作
                            //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                            //记录需要下架的商品id。执行结束后统一删除
                            goodsIds.add(vo.getGoodsId());

                            //向前端发送下架信息
                            vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                            vo.setReason("发货时间超过48小时");
                            count++;
                            res = new JSONObject();
                            res.put("action","list");
                            res.put("data",vo);
                            res.put("count",count);
                            webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                            continue;
                        }
                    }
                }
            }

            if(tlPddMall.getBaoyou().equals("1")) {
                //判断运费是否包邮或者运费0元起
                if(!tlDyDoodsDetail.getLogisticsInfo().contains("包邮")) {
                    Integer money = arr.length == 2 ? Integer.valueOf(arr[1].replaceAll("[^0-9]", "")) : Integer.valueOf(arr[2].replaceAll("[^0-9]", ""));
                    if(money != 0) {
                        //不包邮且运费不是0元起，执行下架操作
                        //pddGoodsSaleStatusSet(tlPddToken.getAccessToken());
                        //记录需要下架的商品id。执行结束后统一删除
                        goodsIds.add(vo.getGoodsId());

                        //向前端发送下架信息
                        vo.setOuterGoodsId(skuVo.getOuterGoodsId());
                        vo.setReason("不包邮");
                        count++;
                        res = new JSONObject();
                        res.put("action","list");
                        res.put("data",vo);
                        res.put("count",count);
                        webSocketServer.sendInfo(res.toJSONString(),userId.toString());

                        continue;
                    }
                }
            }
            count++;
            res = new JSONObject();
            res.put("action","tongbu");
            res.put("count",count);
            webSocketServer.sendInfo(res.toJSONString(),userId.toString());
        }
        //批量删除
        if(goodsIds.size() > 0) {
            tlPddGoodsService.deleteTlPddGoodsByGoodsIds(goodsIds.toArray(new Long[goodsIds.size()]));
            tlPddGoodsSkuService.deleteTlPddGoodsSkuByGoodsIds(goodsIds.toArray(new Long[goodsIds.size()]));
            tlPddGoodsSpecService.deleteTlPddGoodsSpecByGoodsIds(goodsIds.toArray(new Long[goodsIds.size()]));
        }
        return AjaxResult.success(1);
    }

    public void pddGoodsSaleStatusSet(String accessToken) throws Exception{
        //执行拼多多下架操作
        PopClient client = new PopHttpClient(clientId, clientSecret);
        PddGoodsSaleStatusSetRequest request = new PddGoodsSaleStatusSetRequest();
        request.setGoodsId(0L);
        request.setIsOnsale(0);
        PddGoodsSaleStatusSetResponse response = client.syncInvoke(request, accessToken);
    }
}
